package com.yang.modules.common.config;

import com.yang.modules.common.config.properties.ThreadPoolProperty;
import com.yang.modules.common.threadpool.CustomThreadPoolTaskExecutor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;


import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: Billyang
 * @date: 2024/9/17 16:43
 */
@Configuration
@ConditionalOnProperty(prefix = "template", name = "thread-pool.maxPoolSize")
@EnableConfigurationProperties(ThreadPoolProperty.class)
public class ThreadPoolConfiguration {

    @Bean(destroyMethod = "destroy")
    ThreadPoolTaskExecutor threadPoolTaskExecutor(ThreadPoolProperty properties) {
        ThreadPoolTaskExecutor executor = new CustomThreadPoolTaskExecutor();
        // 设置线程池核心容量
        executor.setCorePoolSize(properties.getCorePoolSize());
        // 设置线程池最大容量
        executor.setMaxPoolSize(properties.getMaxPoolSize());
        // 设置任务队列长度
        executor.setQueueCapacity(properties.getQueueCapacity());
        // 设置线程超时时间
        executor.setKeepAliveSeconds(properties.getKeepAliveSeconds());
        // 设置线程名称前缀
        executor.setThreadNamePrefix(properties.getThreadNamePrefix());
        // 设置线程池关闭的时候等待所有任务都完成再继续销毁其他的Bean
        executor.setWaitForTasksToCompleteOnShutdown(properties.getWaitForTasksToCompleteOnShutdown());
        // 设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住。
        executor.setAwaitTerminationSeconds(properties.getAwaitTerminationSeconds());
        // 设置任务丢弃后的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }
}
